﻿using IMPL.Helpers;
using IMPL.Reused;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace IMPL.Controls
{
    class ImagePanelContainer
    {
        private List<ImagePanel> panels;
        private ImagePanel selectedPanel = null;

        public WrapPanel MainPanel { get; private set; }

        public ImagePanelContainer(WrapPanel mainPanel)
        {
            this.panels = new List<ImagePanel>();
            this.MainPanel = mainPanel;
        }

        public void AddPanel(BitmapSource bitmap)
        {
            var newPanel = new ImagePanel(bitmap);
            newPanel.SetMouseDown(imagePanel_MouseDown);

            this.MainPanel.Children.Add(newPanel.ContainingPanel);
            this.panels.Add(newPanel);

            if (selectedPanel == null)
            {
                selectedPanel = newPanel;
                selectedPanel.Selected = true;
            }
        }

        private void imagePanel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (this.selectedPanel.MainPanel != (DockPanel)sender)
            {
                if (this.selectedPanel != null)
                {
                    this.selectedPanel.Selected = false;
                }

                this.selectedPanel = panels.Single(p => p.MainPanel == (DockPanel)sender);
                this.selectedPanel.Selected = true;
            }
        }

        public void ApplyOperation(Lab1.Metody metoda)
        {
            var image = (BitmapImage)((Image)this.selectedPanel.MainPanel.Children[1]).Source;

            var resultBitmap = Lab1.Wyrownanie(new FastBitmap(image), metoda);

            AddPanel(BitmapConverter.Bitmap2BitmapSource(resultBitmap.Bitmap));
        }
    }
}
